from datetime import datetime
import requests
import random
import time
import traceback
import threading  # 导入threading模块

# API地址和基本信息
base_url = 'http://1.117.224.100:81/api'
headers = {
    'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
}

timeout = 3 * 60 * 60
count = 1


# 定义执行请求的函数
def perform_request(thread_name):
    global count
    print(f"{thread_name} 开始时间 {datetime.now()}")

    # 打开error.txt文件，准备写入错误信息
    with open(f'error_{thread_name}.txt', 'w', encoding='utf-8') as error_file:
        # 循环运行直到超时
        start_time = time.time()
        while time.time() - start_time < timeout:
            try:
                response = requests.get(
                    f"{base_url}/banners"
                )
                print(f"{thread_name} {count} 执行成功")
                count += 1
                # time.sleep(1)

                if response.status_code != 200:
                    error_message = f"{thread_name} 访问失败,状态码{response.status_code},{response.text}"
                    error_file.write(error_message + '\n')
                    break


            except Exception as e:
                print(e)
                print(f"{thread_name} 异常时间 {datetime.now()},{count}")
                # 打印异常信息并写入到error.txt文件
                error_traceback = traceback.format_exc()
                print(error_traceback)
                error_file.write(f'{thread_name} 出现异常：{error_traceback}\n')
                break


# 创建线程
thread1 = threading.Thread(target=perform_request, args=("Thread-1",))
thread2 = threading.Thread(target=perform_request, args=("Thread-2",))
thread3 = threading.Thread(target=perform_request, args=("Thread-3",))
thread4 = threading.Thread(target=perform_request, args=("Thread-4",))
thread5 = threading.Thread(target=perform_request, args=("Thread-5",))

# 启动线程
thread1.start()
thread2.start()
thread3.start()
thread4.start()
thread5.start()

# 等待所有线程完成
thread1.join()
thread2.join()
thread3.join()
thread4.join()
thread5.join()
